class VacationPlannerReader 
  require 'enumerator'
  def initialize(file_contents)
    @vp_data = file_contents
  end

  def each
    @vp_data.each_line do |line|
      event = build_event_from_vp_entry(line)
      yield event if !event.nil? 
    end
  end

	def preprocess_vp_entry(vp_entry) 
		vp_entry_as_byte_array = vp_entry.bytes.to_a
		# Removes a nasty non-utf-8 encoded character
		vp_entry_as_byte_array.delete(0xFF)
    vp_entry.replace(vp_entry_as_byte_array.map {|byte| byte.chr}.join)
	end

  def build_event_from_vp_entry(vp_entry)
    preprocess_vp_entry(vp_entry)
    if line =~ /(\d{2})\/(\d{2})\/(\d{4})(\d{12})(.*)/
      details = $5
      result  = Event.new 

      year   = $3.to_i
      month  = $2.to_i
      day    = $1.to_i
      hour   = 8
      minute = 0

      duration = 8.hours

      case details 
      when /HF/ 
        result.title = "PC Vacation"
        result.event_type = Event::PC_HOLIDAY
        result.description = details[2, details.length - 2]
      when /SF(.*)/ 
        result.title = "Site Holiday"
        result.event_type = Event::SITE_HOLIDAY
        result.description = details[2, details.length - 2]
      when /VF/
        result.title = "Vacation"
        result.event_type = Event::VACATION
        result.description = details[2, details.length - 2]
      when /Dr Appt(\d{1,2})?:?(\d\d)?(pm|am|PM|AM)?/
        result.title = "Dr Appt"
        result.event_type = Event::REGULAR

        if !$1.nil?
          hour = $1.to_i
          if !$3.nil? && $3.downcase == "pm" && hour < 12
            hour += 12 
          end
        end
        if !$2.nil?
          minute = $2.to_i
        end
        duration = 3.hours
      end

      result.begin_date = DateTime.new(year, month, day, hour, minute)
      result.end_date   = result.begin_date + duration

      if duration == 8.hours
        result.duration_type = FULL_DAY
      else
        if result.begin_date.hour < 12
          result.duration_type = AM
        else
          result.duration_type = PM
        end
      end

      return result 
    else
      return nil
    end
  end
end

  
